package com.yifeng.repo.controller.traffic.in.processor.worker;

import java.util.ServiceLoader;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Created by daibing on 2021/11/21.
 */
public class TrafficInWorkerFactory {
    private static final ConcurrentMap<String, TrafficInWorker> IMPL_MAPPING = new ConcurrentHashMap<>(2);

    static {
        ServiceLoader<TrafficInWorker> serviceLoader = ServiceLoader.load(TrafficInWorker.class);
        for (TrafficInWorker worker : serviceLoader) {
            try {
                register(worker);
            } catch (Exception e) {
                // ignore error when load spring bean
            }
        }
    }

    /**
     * 如果实现类是Spring Bean，需要手工注册或者使用TrafficInWorkerSpringFactory注册
     */
    public static void register(TrafficInWorker worker) {
        String clazz = worker.getClass().getName();
        IMPL_MAPPING.put(clazz, worker);
    }

    public static TrafficInWorker get(String workerClassName) {
        TrafficInWorker worker = IMPL_MAPPING.get(workerClassName);
        if (worker == null) {
            throw new RuntimeException("Not found TrafficInWorker impl by workerClassName: " + workerClassName);
        }
        return worker;
    }
}
